<?php

namespace App\Http\Controllers;

use App\Models\Contact;
use App\Models\ContactMethod;
use App\Models\ContactRecord;
use App\Models\Group;

use Exception;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ContactController extends Controller
{
    public function contactList(Request $request){
        $group_id = $request->get('group',$request->session()->get('group',0));
        $s_name = $request->get('s_name',$request->session()->get('s_name',''));
        $count_per_page = $request->get('count_per_page',$request->session()->get('count_per_page',10));
        $order_by = $request->get('order_by',$request->session()->get('order_by','id'));
        $order_by = $order_by? : 'id';
        $order = $request->get('order',$request->session()->get('order','down'));
        $sort_order = $order=='down'? 'desc' : 'asc';

        $request->session()->put('group',$group_id);
        $request->session()->put('s_name',$s_name);
        $request->session()->put('count_per_page',$count_per_page);
        $request->session()->put('order_by',$order_by);
        $request->session()->put('order',$order);


        if($group_id>0){
            $group = Group::find($group_id+0);
            $contacts = $group->contacts()->where(function(Builder $q) use ($s_name){
                $q->where('first_name','like','%'.$s_name.'%')
                    ->orWhere('last_name','like','%'.$s_name.'%');
            })->orderBy($order_by,$sort_order)->paginate($count_per_page);
        }
        else{
            $contacts = Contact::where('first_name','like','%'.$s_name.'%')
                ->orWhere('last_name','like','%'.$s_name.'%')->orderBy($order_by,$sort_order)->paginate($count_per_page);
        }

        $groups = Group::all();
        $message = $request->session()->get('message','');
        $request->session()->remove('message');
        return view('contact.contact-list')->with([
            'contacts'=>$contacts,
            'groups'=>$groups,
            'group_id'=>$group_id,
            's_name'=>$s_name,
            'count_per_page'=>$count_per_page,
            'order_by'=>$order_by,
            'order'=>$order,
            'message'=>$message,
        ]);
    }

    public function delete(Request $request){
        $id = $request->get('id',0);
        if($id){
            if(Contact::destroy($id+0)){
                $request->session()->put('message','The record has been deleted successfully.');
            }
            else{
                $request->session()->put('message',"The record can't be found!");
            }
        }
        return response()->redirectToRoute('contact-list');
    }
    public function new(){
        $groups = Group::orderBy('name')->get();
        $methods = ContactMethod::orderBy('name')->get();
        $titles = Contact::select('title')->distinct()->pluck('title');
        return view('contact.new-contact')->with([
            'titles'=>$titles,
            'groups'=>$groups,
            'methods'=>$methods,
        ]);
    }

    public function create(Request $request){
        //return view('check')->with(['inputs'=>$request->all()]);
        //$request->flash();
        $validated = $request->validate([
            'first_name' => 'required',
            'last_name' => 'required'
        ]);
        $first_name = $request->get("first_name");
        $last_name = $request->get("last_name");
        $title = $request->get("title");
        $modified_group_ids = $request->get('modified_group_ids',[]);
        $modified_group_names = $request->get('modified_group_names',[]);
        $deleted_group_ids = $request->get('deleted_group_ids',[]);
        $joined_group_ids = $request->get('joined_group_ids',[]);
        $joined_group_names = $request->get('joined_group_names',[]);
        $added_group_names = $request->get('added_group_names',[]);
        $methods = $request->get('methods',[]);
        $records = $request->get('records',[]);


        /* save modified groups
        [modified_group_ids] => Array
        (
            [0] => 4
            [1] => 5
        )

        [modified_group_names] => Array
        (
            [0] => Business123
            [1] => Relative
        )
        */
        foreach($modified_group_ids as $idx=>$id){
            $group = Group::find($id+0);
            if($group){
                $group->name = $modified_group_names[$idx];
                $group->save();
            }
        }

        /* delete groups
        [deleted_group_ids] => Array
        (
            [0] => 1
        )
        */
        foreach($deleted_group_ids as $gid){
            Group::destroy($gid+0);
        }

        /* add new groups
        [added_group_names] => Array
        (
            [0] => Dog
            [1] => Cat
        )

        */
        foreach ($added_group_names as $name){
            $group = new Group();
            $group->name = $name;
            $group->save();
        }

        DB::beginTransaction();
        try {
            $contact = new Contact();
            $contact->first_name = $first_name;
            $contact->last_name = $last_name;
            $contact->title = $title;
            $contact->save();
            /*
             * [joined_group_ids] => Array
            (
                [0] => 4
                [1] => 3
                [2] => 0
            )

             [joined_group_names] => Array
            (
                [0] => Business123
                [1] => Classmate
                [2] => Dog
            )

             */
            foreach($joined_group_ids as $idx=>$gid){
                if($gid=='0'){
                    $group = Group::where('name',$joined_group_names[$idx])->firstOrFail();
                    $gid = $group->id;
                }
                $contact->groups()->attach($gid+0);
            }
            /* save new method
            [methods] => Array
            (
                [0] => Email
                [1] => Email
                [2] => Mobile
                [3] => Tele
            )

            [records] => Array
            (
                [0] => abc@gmail.com
                [1] => def@gmail.com
                [2] => 15634525879
                [3] => 123-456-7890
            )
            */
            foreach($methods as $method){
                if(ContactMethod::where('name',$method)->count()==0){
                    $cm = new ContactMethod();
                    $cm->name = $method;
                    $cm->save();
                }
            }
            // save records
            foreach($methods as $idx=>$method) {
                $rec = new ContactRecord();
                $rec->contact_method_id = ContactMethod::where('name',$method)->firstOrFail()->id;
                $rec->record = $records[$idx];
                $rec->contact()->associate($contact);
                $rec->save();
            }
            DB::commit();
            $request->session()->put("message","Contact added successfully!");
        }catch (Exception $e){
            DB::rollBack();
            $request->session()->put("message",$e->getMessage());
        }
        return response()->redirectToRoute("contact-list");
    }
}
